<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta name="description" content="理解Rust的引用和借用"><meta name="keywords" content="Rust"><meta name="author" content="LiYang"><meta name="copyright" content="LiYang"><title>理解Rust的引用和借用 | 一条鲤鱼</title><link rel="shortcut icon" href="/melody-favicon.ico"><link rel="stylesheet" href="/css/index.css?version=1.9.0"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css?version=1.9.0"><meta name="format-detection" content="telephone=no"><meta http-equiv="x-dns-prefetch-control" content="on"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  hexoVersion: '5.4.0'
} </script><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="一条鲤鱼" type="application/atom+xml">
</head><body><i class="fa fa-arrow-right" id="toggle-sidebar" aria-hidden="true"></i><div id="sidebar" data-display="true"><div class="toggle-sidebar-info text-center"><span data-toggle="Toggle article">Toggle site</span><hr></div><div class="sidebar-toc"><div class="sidebar-toc__title">Catalog</div><div class="sidebar-toc__progress"><span class="progress-notice">You've read</span><span class="progress-num">0</span><span class="progress-percentage">%</span><div class="sidebar-toc__progress-bar"></div></div><div class="sidebar-toc__content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF%E5%80%9F%E7%94%A8%EF%BC%9F"><span class="toc-number">1.</span> <span class="toc-text">什么是借用？</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%BC%95%E7%94%A8%E5%92%8C%E5%80%9F%E7%94%A8"><span class="toc-number">2.</span> <span class="toc-text">引用和借用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-number">3.</span> <span class="toc-text">总结</span></a></li></ol></div></div><div class="author-info hide"><div class="author-info__avatar text-center"><img src="/img/avatar.png"></div><div class="author-info__name text-center">LiYang</div><div class="author-info__description text-center"></div><hr><div class="author-info-articles"><a class="author-info-articles__archives article-meta" href="/archives"><span class="pull-left">Articles</span><span class="pull-right">13</span></a><a class="author-info-articles__tags article-meta" href="/tags"><span class="pull-left">Tags</span><span class="pull-right">6</span></a><a class="author-info-articles__categories article-meta" href="/categories"><span class="pull-left">Categories</span><span class="pull-right">7</span></a></div></div></div><div id="content-outer"><div class="no-bg" id="top-container"><div id="page-header"><span class="pull-left"> <a id="site-name" href="/">一条鲤鱼</a></span><i class="fa fa-bars toggle-menu pull-right" aria-hidden="true"></i><span class="pull-right menus">   <a class="site-page" href="/">Home</a><a class="site-page" href="/archives">Archives</a><a class="site-page" href="/tags">Tags</a><a class="site-page" href="/categories">Categories</a></span><span class="pull-right"></span></div><div id="post-info"><div id="post-title">理解Rust的引用和借用</div><div id="post-meta"><time class="post-meta__date"><i class="fa fa-calendar" aria-hidden="true"></i> 2021-09-22</time><span class="post-meta__separator">|</span><i class="fa fa-inbox post-meta__icon" aria-hidden="true"></i><a class="post-meta__categories" href="/categories/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/">编程语言</a></div></div></div><div class="layout" id="content-inner"><article id="post"><div class="article-container" id="post-content"><p>​    学习了一段时间的Rust编程语言后，对Rust中的<strong>引用（References）</strong>和<strong>借用（borrowing）</strong>产生了一些疑问：</p>
<ul>
<li>1、对比C++中的引用，rust中的引用是否也是变量别名，作为变量附属在内存位置中的第二个标签？</li>
<li>2、&amp;关键字是代表引用还是借用？</li>
<li>3、ref和&amp;有什么区别？</li>
</ul>
<hr>
<p>​    看了几本书中的介绍，对rust中的引用和借用描述的云里雾里的，比如<strong>《Rust编程 入门、实战与进阶》</strong>一书中对引用和借用的介绍如下：引用是一种语法（本质上是Rust提供的一种指针语义），而借用（Borrowing）是对引用行为的描述。引用分为不可变引用和可变引用，对应着不可变借用和可变借用。</p>
<p>​    这样说完，是不是更晕了呢。不如我们从代码入手，分析一下到底什么是Rust中的引用，什么是Rust中的借用。这里笔者说下自己的理解。</p>
<hr>
<h2 id="什么是借用？"><a href="#什么是借用？" class="headerlink" title="什么是借用？"></a>什么是借用？</h2><p>根据笔者看过的基本Rust编程语言的教学入门书籍，都是从Rust较与其他语言所提出的新概念：借用 来介绍的。那我们不妨从为什么借用开始：</p>
<p>​    首先，看下面这段代码：</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">fn</span> <span class="title">main</span></span>() &#123;</span><br><span class="line">    <span class="keyword">let</span> s1 = <span class="built_in">String</span>::from(<span class="string">&quot;hello&quot;</span>);</span><br><span class="line">    <span class="keyword">let</span> len = calculate_length(&amp;s1);</span><br><span class="line">    <span class="built_in">println!</span>(<span class="string">&quot;The length of &#x27;&#123;&#125;&#x27; is &#123;&#125;.&quot;</span>, s1, len);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">fn</span> <span class="title">calculate_length</span></span>(s: &amp;<span class="built_in">String</span>) -&gt; <span class="built_in">usize</span> &#123;<span class="comment">// s 是对 String 的借用</span></span><br><span class="line">    s.len()</span><br><span class="line">&#125;<span class="comment">// 这里，s 离开了作用域。但因为它并不拥有借用值的所有权，</span></span><br><span class="line">  <span class="comment">// 所以什么也不会发生</span></span><br></pre></td></tr></table></figure>

<ul>
<li>这里，我们需要使用借用，因为我们要在不获得s1的所有权的情况下使用s1的值，这就是“借（borrow）“的含义。**&amp; 符号就是借用，它们允许你使用值但不获取其所有权。**</li>
<li>从内存管理来看，这段代码在内存上做的工作如下图所示：</li>
</ul>
<p><img src="/2021/09/22/%E7%90%86%E8%A7%A3Rust%E7%9A%84%E5%BC%95%E7%94%A8%E5%92%8C%E5%80%9F%E7%94%A8/1.1.png" alt="1.1"></p>
<p>​                                            <em>图1.1：<code>&amp;String s</code> 指向 <code>String s1</code> 示意图</em></p>
<ul>
<li>根据示意图，我们知道，所谓借用，就是将一个指针的值域指向需要被借用的变量，这样就能够在不取走原本变量对值的所有权的情况下，使用其所有的值。这样说，听起来有些绕，但是这就是Rust所有权系统的含义之一，与<strong>生命周期</strong>结合起来理解，<code>&amp;s1</code> 语法让我们创建一个 <strong>指向</strong> 值 <code>s1</code> 的引用，但是并不拥有它。因为并不拥有这个值，当引用离开作用域时其指向的值也不会被丢弃。</li>
<li>借用默认是只读的，想要修改借用的值，可以使用<strong>可变引用&amp;mut</strong>，这里就不展开讲了。</li>
<li>另外，与使用 <code>&amp;</code> 借用相反的操作是 <strong>解引用</strong>（<em>dereferencing</em>），它使用解引用运算符，<code>*</code>。</li>
</ul>
<h2 id="引用和借用"><a href="#引用和借用" class="headerlink" title="引用和借用"></a>引用和借用</h2><p>​    简单介绍了Rust中的借用，我们发现，借用的意义确实像是C++等语言中的引用，是用来间接访问对象的一种手段。那么什么是Rust中的引用呢？</p>
<ul>
<li><p><strong>rust中借用和引用的附带功效都一样，就是都有生命周期。借用使用&amp;关键字，引用使用ref关键字。借用的对象是必须存在的，引用的对象可以虚拟的，后期附上对象。</strong>这也是与c++语言中引用不同的地方，c++ 语言说的是，引用类似变量别名，声明引用时，必须同时对其进行初始化。</p>
</li>
<li><p>再看下出自《Programming Rust Fast, Safe Systems Development》</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">in Rust terminology, we say that it borrows a reference to x. Given a</span><br><span class="line">reference r, the expression *r refers to the value r points to. These are very much like</span><br><span class="line">the &amp; and * operators in C and C++</span><br><span class="line">Unlike C pointers, however, Rust references are never null: there is simply no way to</span><br><span class="line">produce a null reference in safe Rust. And Rust references are immutable by default</span><br></pre></td></tr></table></figure>

<p>书中将rust的引用与c++的指针进行了比较。</p>
</li>
<li><p>我们还是从代码入手，看一下rust语言中引用到底是什么：</p>
<ul>
<li><p>首先实践，引用能否为空：</p>
<figure class="highlight rust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> <span class="keyword">ref</span> a:<span class="built_in">i32</span>;</span><br><span class="line">a = &amp;<span class="number">1</span>;</span><br></pre></td></tr></table></figure></li>
<li><p>上面代码能编译通过，<strong>这说明Rust中的引用和c++ 中的引用不是一个意思，更像c++ 中的指针类型</strong>。c++ 通过<code>int *a</code>来声明指针类型。</p>
</li>
</ul>
</li>
<li><p>再来分析一下引用（ref）和借用（&amp;）的区别：</p>
<ul>
<li>```rust<br>let ref a=2;//&amp;i32<br>let a = &2;//&amp;i32<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">  * 编译器告诉我们，两个值都是`&amp;i32`类型。</span><br><span class="line"></span><br><span class="line">  * 所以`ref`用在变量绑定与`&amp;`用在表达式上是一样的效果。</span><br><span class="line"></span><br><span class="line">* 加深一下理解，我们直接通过代码输出告诉我们&amp;和ref的类型是什么：</span><br><span class="line"></span><br><span class="line">  ```rust</span><br><span class="line">  fn main() &#123;</span><br><span class="line">      let x = &amp;false;</span><br><span class="line">      print_type_name_of(x);</span><br><span class="line">  </span><br><span class="line">      let &amp;y = &amp;false;</span><br><span class="line">      print_type_name_of(y);</span><br><span class="line">  </span><br><span class="line">      let ref z = &amp;false;</span><br><span class="line">      print_type_name_of(z);</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  fn print_type_name_of&lt;T&gt;(_: T) &#123;</span><br><span class="line">      println!(&quot;&#123;&#125;&quot;, unsafe &#123; std::intrinsics::type_name::&lt;T&gt;() &#125;)</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li><p>通过输出结果，我们知道了x是&amp;bool类型，y是bool类型，z是&amp;&amp;bool类型。</p>
</li>
</ul>
<p>除此之外，Rust中的引用和借用还有一个要注意的地方：<strong>match的模式匹配上只能使用 <code>ref</code>，在函数声明上只能使用<code>&amp;</code>来表示引用类型。</strong></p>
<hr>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p><strong>Rust中&amp;在不同情况下的意思：</strong></p>
<ol>
<li>在表达式上，表示的是借用。</li>
<li>在变量绑定上，表示解地址操作与*类似。</li>
<li>在类型声明上，表示引用类型。</li>
<li>在模式匹配上，<strong>无效关键字，应使用ref。</strong></li>
</ol>
<p><strong>Rust中ref的解释：</strong></p>
<ol>
<li>在表达式上，<strong>无效关键字</strong>。</li>
<li>在变量绑定上，表示引用类型。</li>
<li>在类型声明上，<strong>无效关键字</strong>。</li>
<li>在模式匹配上，表示引用类型。</li>
</ol>
<p>​    如果非要给区分<code>ref</code>和<code>&amp;</code>到底哪个是引用，哪个是借用。我们可以先从词性划分，引用我归类为名词，而借用归类为动词。<code>&amp;A</code>在表达式上 表示借用A，这是一个动作，那结果就是产出一个引用类型。所以<code>let ref B</code>表示声明了一个引用类型，它只能绑定到某次借用动作上。</p>
<p><strong>所以<code>ref</code> 更适合叫引用， <code>&amp;</code>叫借用。</strong></p>
</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">Author: </span><span class="post-copyright-info"><a href="mailto:undefined">LiYang</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">Link: </span><span class="post-copyright-info"><a href="http://example.com/2021/09/22/理解Rust的引用和借用/">http://example.com/2021/09/22/理解Rust的引用和借用/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">Copyright Notice: </span><span class="post-copyright-info">All articles in this blog are licensed under <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> unless stating additionally.</span></div></div><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Rust/">Rust</a></div><nav id="pagination"><div class="prev-post pull-left"><a href="/2021/09/22/Rust%E7%9A%84Option%E7%9A%84%E6%AD%A3%E7%A1%AE%E6%89%93%E5%BC%80%E6%96%B9%E5%BC%8F/"><i class="fa fa-chevron-left">  </i><span>Rust的Option的正确打开方式</span></a></div><div class="next-post pull-right"><a href="/2021/09/15/Rust%E4%B8%AD%E7%9A%84Rc%E5%92%8CBox-leak-%E6%9C%BA%E5%88%B6/"><span>Rust中的Rc、Arc和Box::leak()机制</span><i class="fa fa-chevron-right"></i></a></div></nav></div></div><footer><div class="layout" id="footer"><div class="copyright">&copy;2013 - 2022 By LiYang</div><div class="framework-info"><span>Driven - </span><a target="_blank" rel="noopener" href="http://hexo.io"><span>Hexo</span></a><span class="footer-separator">|</span><span>Theme - </span><a target="_blank" rel="noopener" href="https://github.com/Molunerfinn/hexo-theme-melody"><span>Melody</span></a></div><div class="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_page_pv"><i class="fa fa-file"></i><span id="busuanzi_value_page_pv"></span><span></span></span></div></div></footer><i class="fa fa-arrow-up" id="go-up" aria-hidden="true"></i><script src="https://cdn.jsdelivr.net/npm/animejs@latest/anime.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@latest/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@latest/velocity.ui.min.js"></script><script src="/js/utils.js?version=1.9.0"></script><script src="/js/fancybox.js?version=1.9.0"></script><script src="/js/sidebar.js?version=1.9.0"></script><script src="/js/copy.js?version=1.9.0"></script><script src="/js/fireworks.js?version=1.9.0"></script><script src="/js/transition.js?version=1.9.0"></script><script src="/js/scroll.js?version=1.9.0"></script><script src="/js/head.js?version=1.9.0"></script><script>if(/Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent)) {
  $('#nav').addClass('is-mobile')
  $('footer').addClass('is-mobile')
  $('#top-container').addClass('is-mobile')
}</script></body></html>